/**
* Created with CLion.
* User:Lenovo
* Date:2023-05-18
* Time:4:17
* Description:
*/

#include "Stack.h"

void STInit(ST *pst)
{
    assert(pst);// 断言，保证 pst 不为空

    pst -> a = NULL;
    pst -> top = 0;// 思考：top 是 0，指向的是栈顶元素吗？ 是 -1 呢？
    // pst -> top = -1;
    pst -> capacity = 0;
}

void STDestroy(ST *pst)
{
    assert(pst);

    free(pst -> a);
    pst -> a = NULL;
    pst -> top = pst -> capacity = 0;
}


void STPush(ST *pst, STDataType x)
{
    assert(pst);

    if (pst -> top == pst -> capacity)
    {
        int newCapacity = pst -> capacity == 0 ? 4 : pst -> capacity * 2;
        STDataType *tmp = (STDataType *)realloc(pst -> a, newCapacity * sizeof(STDataType));
        if (tmp == NULL)
        {
            perror("realloc failed");
            return;
        }
        pst -> a = tmp;
        pst -> capacity = newCapacity;
    }

    pst -> a[pst -> top] = x;
    pst -> top++;
}

void STPop(ST *pst)
{
    assert(pst);
    assert(!STEmpty(pst));// 判空

    pst -> top--;
}

STDataType STTop(ST *pst)
{
    assert(pst);
    assert(!STEmpty(pst));

    return pst -> a[pst -> top - 1];
}

bool STEmpty(ST *pst)
{
    return pst -> top == 0;
    // return !(pst -> top);
}

int STSize(ST *pst)
{
    assert(pst);

    return pst -> top;
}
